package com.example.hjt_java_web_homework3.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author Li Chun Hei
 * @date 31/10/2025
 * @description
 */
public class BaseServlet extends HttpServlet {
    protected static final Logger logger = LogManager.getLogger(BaseServlet.class);
    protected static final ObjectMapper objectMapper = new ObjectMapper();

    protected String getRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString();
    }

    protected void sendJsonResponse(HttpServletResponse response, Object data) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        objectMapper.writeValue(response.getWriter(), data);
    }

    protected void sendErrorResponse(HttpServletResponse response, int status, String message) throws IOException {
        response.setStatus(status);
        sendJsonResponse(response, new ErrorResponse(message));
    }

    protected void sendSuccessResponse(HttpServletResponse response, Object data) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        sendJsonResponse(response, new SuccessResponse(data));
    }

    // 内部响应类
    public static class SuccessResponse {
        private boolean success = true;
        private Object data;

        public SuccessResponse(Object data) {
            this.data = data;
        }

        public boolean isSuccess() { return success; }
        public Object getData() { return data; }
    }

    public static class ErrorResponse {
        private boolean success = false;
        private String message;

        public ErrorResponse(String message) {
            this.message = message;
        }

        public boolean isSuccess() { return success; }
        public String getMessage() { return message; }
    }
}
